<template>
  <div class="component-upload-image">
    <el-upload
      :multiple="false"
      :action="uploadUrl"
      :headers="headers"
      list-type="picture-card"
      :limit="limit"
      :on-preview="handlePictureCardPreview"
      :on-change="handleChange"
      :on-success="handleUploadSuccess"
      :on-remove="removeFile"
      :on-error="handleUploadError"
      :file-list="fileList"
      :class="{ disabled: uploadDisabled }"
    >
      <el-icon class="avatar-uploader-icon"><plus /></el-icon>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
import { uploadImage } from "@/api/base";
const props = defineProps({
  limit: {
    type: Number,
    default: 1,
  },
  fileList: {
    type: Array,
    default: () => [],
  },
});
const emit = defineEmits(["fileChange"]);

const uploadUrl = `${import.meta.env.VITE_APP_BASE_API}/common/upload`;
const headers = ref({
  Authorization: "Bearer " + getToken(),
});

const _fileList = ref([]);
const uploadDisabled = computed(() => {
  return _fileList.value.length >= props.limit;
});

watch(
  () => props.fileList,
  (newVal) => {
    _fileList.value = newVal.map((item) => ({
      name: item.fileName,
      url: item.url,
      status: "success",
      uid: item.uid,
    }));
  },
  { immediate: true }
);

const handleChange = (file) => {
  console.log("[ file ] >", file);
};

const handleUploadSuccess = (data, file) => {
  _fileList.value.push({
    name: file.fileName,
    url: data.url,
    status: "success",
    uid: file.uid,
  });
  emit("fileChange", _fileList.value);
};
const removeFile = (file) => {
  _fileList.value = _fileList.value.filter((item) => item.uid !== file.uid);
  emit("fileChange", _fileList.value);
};

const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};
const handleUploadError = (error, file) => {
  emit("error", error, file, _fileList.value);
};
</script>

<style scoped>
.component-upload-image {
  display: flex;
  align-items: center;
  justify-content: center;
}
.disabled :deep(.el-upload--picture-card) {
  display: none !important;
}
</style>
